<template>
  <div class="app-container">
    <el-card>
      <div class="card-header">
        <div class="title">纠纷详情</div>
        <div class="right">
          <el-button type="primary" size="small" @click="goBack">返回列表</el-button>
          <el-button type="success" size="small" @click="refreshData">刷新</el-button>
        </div>
      </div>

      <div class="dispute-container" v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card class="box-card">
              <div slot="header" class="dispute-header">
                <span class="dispute-title">纠纷基本信息</span>
                <el-tag :type="getStatusType(disputeDetail.status)">{{ getStatusText(disputeDetail.status) }}</el-tag>
              </div>
              <el-descriptions :column="3" border>
                <el-descriptions-item label="纠纷ID">{{ disputeDetail.id }}</el-descriptions-item>
                <el-descriptions-item label="订单编号">
                  <router-link :to="'/admin/order/detail/' + disputeDetail.orderId" class="link-type">
                    {{ disputeDetail.orderNo }}
                  </router-link>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDate(disputeDetail.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="客户名称">{{ disputeDetail.customerName }}</el-descriptions-item>
                <el-descriptions-item label="纠纷类型">{{ disputeDetail.disputeType }}</el-descriptions-item>
                <el-descriptions-item label="处理状态">
                  <el-tag :type="getStatusType(disputeDetail.status)">{{ getStatusText(disputeDetail.status) }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="纠纷描述" :span="3">
                  {{ disputeDetail.description }}
                </el-descriptions-item>
                <el-descriptions-item label="证据图片" :span="3" v-if="disputeDetail.evidenceImages">
                  <el-image
                    v-for="(img, index) in disputeDetail.evidenceImages.split(',')"
                    :key="index"
                    :src="img"
                    :preview-src-list="disputeDetail.evidenceImages.split(',')"
                    fit="cover"
                    class="evidence-image"
                  />
                </el-descriptions-item>
                <el-descriptions-item 
                  label="处理人员" 
                  v-if="disputeDetail.processorName">
                  {{ disputeDetail.processorName }}
                </el-descriptions-item>
                <el-descriptions-item 
                  label="处理时间" 
                  v-if="disputeDetail.processTime">
                  {{ formatDate(disputeDetail.processTime) }}
                </el-descriptions-item>
                <el-descriptions-item 
                  label="解决方案" 
                  :span="3" 
                  v-if="disputeDetail.resolution">
                  {{ disputeDetail.resolution }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="communication-row">
          <el-col :span="24">
            <el-card class="box-card">
              <div slot="header" class="dispute-header">
                <span class="dispute-title">沟通记录</span>
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleAddCommunication"
                  v-if="disputeDetail.status === 'pending' || disputeDetail.status === 'processing'"
                >
                  添加回复
                </el-button>
              </div>
              <div class="timeline-container">
                <el-timeline v-if="disputeDetail.communicationLogs && disputeDetail.communicationLogs.length > 0">
                  <el-timeline-item
                    v-for="(log, index) in disputeDetail.communicationLogs"
                    :key="index"
                    :timestamp="formatDate(log.sendTime)"
                    :type="log.senderType === 'admin' ? 'primary' : 'info'"
                  >
                    <div class="timeline-content">
                      <div class="sender">{{ log.senderName }} ({{ log.senderType === 'admin' ? '客服' : '客户' }})</div>
                      <div class="message">{{ log.content }}</div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div class="empty-data" v-else>暂无沟通记录</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="order-row">
          <el-col :span="24">
            <el-card class="box-card">
              <div slot="header" class="dispute-header">
                <span class="dispute-title">相关订单信息</span>
                <router-link :to="'/admin/order/detail/' + disputeDetail.orderId" class="link-type">
                  <el-button type="primary" size="small">查看订单详情</el-button>
                </router-link>
              </div>
              <el-descriptions :column="3" border v-if="disputeDetail.orderInfo">
                <el-descriptions-item label="订单编号">{{ disputeDetail.orderInfo.orderNo }}</el-descriptions-item>
                <el-descriptions-item label="商品名称">{{ disputeDetail.orderInfo.productName }}</el-descriptions-item>
                <el-descriptions-item label="订单金额">¥{{ disputeDetail.orderInfo.finalPrice || disputeDetail.orderInfo.budget }}</el-descriptions-item>
                <el-descriptions-item label="订单状态">
                  <el-tag :type="getOrderStatusType(disputeDetail.orderInfo.status)">{{ getOrderStatusText(disputeDetail.orderInfo.status) }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="下单时间">{{ formatDate(disputeDetail.orderInfo.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="预计交付日期">{{ formatDate(disputeDetail.orderInfo.deliveryDate) }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>

        <el-row v-if="disputeDetail.status === 'pending' || disputeDetail.status === 'processing'">
          <el-col :span="24">
            <div class="action-bar">
              <el-button type="primary" @click="handleProcess">{{ disputeDetail.status === 'pending' ? '开始处理' : '更新状态' }}</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 处理纠纷对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="disputeForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(disputeDetail.status)">{{ getStatusText(disputeDetail.status) }}</el-tag>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="disputeForm.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option label="处理中" value="processing" v-if="disputeDetail.status === 'pending'" />
            <el-option label="已解决" value="resolved" v-if="disputeDetail.status !== 'rejected'" />
            <el-option label="已拒绝" value="rejected" v-if="disputeDetail.status !== 'resolved'" />
          </el-select>
        </el-form-item>
        <el-form-item label="解决方案">
          <el-input v-model="disputeForm.resolution" type="textarea" :rows="4" placeholder="请输入解决方案或拒绝理由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDisputeProcess">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加沟通记录对话框 -->
    <el-dialog title="添加沟通记录" v-model="communicationDialogVisible" width="600px">
      <el-form :model="communicationForm" label-width="100px">
        <el-form-item label="回复内容">
          <el-input v-model="communicationForm.content" type="textarea" :rows="4" placeholder="请输入回复内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="communicationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCommunication">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDisputeDetail, processDispute } from '@/api/orderManagement'
import { formatDate } from '@/utils/index'

export default {
  name: 'DisputeDetail',
  data() {
    return {
      disputeId: null,
      loading: true,
      disputeDetail: {},
      dialogVisible: false,
      communicationDialogVisible: false,
      disputeForm: {
        status: '',
        resolution: ''
      },
      communicationForm: {
        content: ''
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.disputeDetail.status === 'pending' ? '开始处理纠纷' : '更新纠纷状态'
    }
  },
  created() {
    this.disputeId = this.$route.params.id
    if (this.disputeId) {
      this.fetchData()
    } else {
      this.$router.push('/admin/order/dispute')
    }
  },
  methods: {
    fetchData() {
      this.loading = true
      getDisputeDetail(this.disputeId)
        .then(response => {
          this.disputeDetail = response.data
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          this.$message.error('获取纠纷详情失败')
        })
    },
    getStatusType(status) {
      const statusMap = {
        'pending': 'danger',
        'processing': 'warning',
        'resolved': 'success',
        'rejected': 'info'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'resolved': '已解决',
        'rejected': '已拒绝'
      }
      return statusMap[status] || '未知状态'
    },
    getOrderStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'warning',
        2: 'warning',
        3: 'primary',
        4: 'success',
        5: 'danger'
      }
      return statusMap[status] || 'info'
    },
    getOrderStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待确认',
        2: '生产中',
        3: '已发货',
        4: '已完成',
        5: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    handleProcess() {
      this.disputeForm = {
        status: this.disputeDetail.status === 'pending' ? 'processing' : '',
        resolution: ''
      }
      this.dialogVisible = true
    },
    submitDisputeProcess() {
      if (!this.disputeForm.status) {
        this.$message.error('请选择处理状态')
        return
      }
      
      if (!this.disputeForm.resolution && (this.disputeForm.status === 'resolved' || this.disputeForm.status === 'rejected')) {
        this.$message.error('请输入解决方案或拒绝理由')
        return
      }
      
      const data = {
        status: this.disputeForm.status,
        resolution: this.disputeForm.resolution,
        operatorId: this.$store.getters.userId // 假设有用户ID存储在Vuex中
      }
      
      processDispute(this.disputeId, data)
        .then(() => {
          this.$message.success('纠纷处理成功')
          this.dialogVisible = false
          this.fetchData()
        })
        .catch(err => {
          this.$message.error('纠纷处理失败: ' + err.message)
        })
    },
    handleAddCommunication() {
      this.communicationForm = {
        content: ''
      }
      this.communicationDialogVisible = true
    },
    submitCommunication() {
      if (!this.communicationForm.content) {
        this.$message.error('请输入回复内容')
        return
      }
      
      // 这里应该调用添加沟通记录的API，但由于没有相应的接口，所以只是模拟成功
      this.$message.success('添加回复成功')
      this.communicationDialogVisible = false
      
      // 模拟添加沟通记录成功后刷新数据
      this.fetchData()
    },
    goBack() {
      this.$router.push('/admin/order/dispute')
    },
    refreshData() {
      this.fetchData()
    },
    formatDate
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.dispute-container {
  margin-top: 20px;
}
.communication-row, .order-row {
  margin-top: 20px;
}
.dispute-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dispute-title {
  font-weight: bold;
}
.timeline-container {
  padding: 20px 0;
}
.timeline-content {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}
.sender {
  font-weight: bold;
  margin-bottom: 5px;
}
.message {
  white-space: pre-wrap;
}
.empty-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}
.evidence-image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}
.action-bar {
  margin-top: 20px;
  text-align: center;
}
.link-type {
  color: #409EFF;
  text-decoration: none;
}
.link-type:hover {
  text-decoration: underline;
}
</style> 